package com.eaero.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eaero.CommonResp;
import com.eaero.entity.TraceUser;
import com.eaero.mapper.TraceUserMapper;
import com.eaero.service.ITraceUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eaero.util.SM4Utils;
import com.eaero.vo.CardLoginResponse;
import com.eaero.vo.Login;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zb
 * @since 2023-03-14
 */
@Service
public class TraceUserServiceImpl extends ServiceImpl<TraceUserMapper, TraceUser> implements ITraceUserService {

    @Override
    public CommonResp getUserInfoAll(String userCode) {
        CommonResp commonResp = CommonResp.buildFailMsg("员工卡号信息获取失败！");
        List<TraceUser> users = list(Wrappers.<TraceUser>lambdaQuery()
                .select(TraceUser::getUserCode, TraceUser::getComMobile, TraceUser::getSnrBox, TraceUser::getUserName, TraceUser::getUserDept)
                .eq(StrUtil.isNotEmpty(userCode), TraceUser::getUserCode, userCode));
        if (CollUtil.isNotEmpty(users)) {
            commonResp = CommonResp.buildSucsDataListMsg(users, "数据获取成功！");
        }
        return commonResp;
    }

    @Override
    public CommonResp loginByCard(String cardId) {
        CommonResp commonResp = CommonResp.buildFailMsg("该员工卡无效！");
        TraceUser users = getOne(Wrappers.<TraceUser>lambdaQuery()
                .select(TraceUser::getUserCode)
                .eq(TraceUser::getSnrBox, cardId));
        CardLoginResponse cardLoginResponse = new CardLoginResponse();
        if (ObjectUtil.isNotEmpty(users)) {
            BeanUtil.copyProperties(users, cardLoginResponse);
            cardLoginResponse.setEmpCode(users.getUserCode());
            List<CardLoginResponse> list = new ArrayList<>();
            list.add(cardLoginResponse);
            commonResp = CommonResp.buildSucsDataListMsg(list, "员工数据获取成功");
        }
        return commonResp;
    }

    @Override
    public CommonResp login(Login login) {
        CommonResp commonResp = CommonResp.buildFailMsg("用户账号验证失败！");
        TraceUser user = getOne(Wrappers.<TraceUser>lambdaQuery()
                .select(TraceUser::getUserCode, TraceUser::getUserPwd )
                .eq(TraceUser::getUserCode, login.getUserCode()));

        if (ObjectUtil.isEmpty(user)) {
            return commonResp;
        }

        String dbPassword = SM4Utils.encryptData_CBC(user.getUserPwd());

        if (!StrUtil.equals(dbPassword, login.getUserPassword())) {
            return commonResp;
        }

        return CommonResp.buildSucsDataListMsg(null, "认证成功！");
    }
}
